<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('600px')"
    :title="$t('EDIT_LAYINGMETHOD')"
    :visible="visible"
    @open="open"
    @close="close"
  >
    <div class="flex align-center tabType mb-10" @click="handleClick">
      <span
        v-for="item in erectMethods"
        :key="item.code"
        :data-parentid="item.code"
        class="flex-1"
        :class="curParent.code == item.code?'active':''"
      >{{ item.name }}</span>
    </div>

    <el-table
      ref="tableBox"
      class="w-100 mb-10"
      :data="tableData"
      height="400px"
      size="mini"
      border
    >
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column type="index" :label="$t('SEQUENCE')" align="center" width="140">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="`${curParent.name}${$t('LAYING_METHOD_S')}`" prop="cableLevel">
        <template v-slot="scope">
          <el-input v-if="scope.row.update" v-model.trim="scope.row.name" clearable maxlength="32" />
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('OPERATE')" class-name="operate-cell" width="80">
        <template v-slot="scope">
          <i
            v-if="scope.$index === tableData.length - 1 && tableData.filter(i => i.update).length < 4"
            class="el-icon-plus mr-10 icon-font"
            @click="addRow"
          />
          <i
            v-if="scope.row.update && !scope.row.used"
            class="el-icon-minus icon-font"
            @click="delRow(scope.row, scope.$index)"
          />
        </template>
      </el-table-column>
    </el-table>
    <template v-slot:footer>
      <el-button size="mini" @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button size="mini" type="primary" @click="$debounce(save)">{{ $t('SAVE') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { deepClone } from '@/utils/common'
  import BizDictApi from '@/api/basebiz/BizDictApi'
  import CableSegmentApi from '@/api/oen/CableSegmentApi'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  export default {
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      erectMethods: {
        type: Array,
        default: () => []
      },
      layingmethods: {
        type: Array,
        default: () => []
      }
    },
    inject: ['parentVM'],
    data() {
      return {
        tableData: [],
        methodList: [],
        curParent: {},
        delIds: [] // 需要删除的id
      }
    },
    computed: {
      ...mapGetters(['getUser', 'getUserId'])
    },
    methods: {
      handleClick(event) {
        const parentId = event.target.dataset.parentid
        this.curParent = this.erectMethods.find(i => i.code === parentId) || {}
        this.setTable()
      },
      open() {
        this.curParent = this.erectMethods[0]
        this.methodList = deepClone(this.layingmethods)
        const ids = this.methodList.map(i => i.code)
        if (!ids.length) {
          this.setTable()
          return
        }
        // 获取被使用的敷设方法
        CableSegmentApi.layMethodUsageStatus({ ids: ids.join(',') }).then(res => {
          this.methodList.forEach(item => {
            item.use = false
            if (res[item.code]) {
              item.used = true
            }
          })
          this.setTable()
        })
      },
      setTable() {
        const list = this.methodList.filter(i => i.parentId === this.curParent.code)
        if (list.length) {
          this.tableData = list
          return
        }
        const date = new Date()
        const item = {
          name: '',
          code: `${this.curParent.code}_SELF_${date.getTime()}`,
          empty: true,
          update: true,
          type: 'CABLE_LAY_METHOD',
          parentId: this.curParent.code,
          sort: 1
        }
        this.tableData = [item]
        this.methodList.push(item)
      },
      addRow() {
        const date = new Date()
        const item = {
          name: '',
          code: `${this.curParent.code}_SELF_${date.getTime()}`,
          update: true,
          type: 'CABLE_LAY_METHOD',
          parentId: this.curParent.code,
          sort: this.tableData.slice(-1)[0]['sort'] + 1
        }
        this.tableData.push(item)
        this.methodList.push(item)
      },
      delRow(row, index) {
        // console.log('row', row)
        this.tableData.splice(index, 1)
        const modeIndex = this.methodList.findIndex(i => i.code === row.code)
        this.methodList.splice(modeIndex, 1)
        if ('id' in row) {
          this.delIds.push(row)// 存储需要删除的项
        }
      },
      async save() { // 保存逻辑网段修改
        let bizDictList = this.methodList.filter(i => i.update)
        if (bizDictList.some(i => !i.name && !i.empty)) {
          this.$message.error(this.$t('PLEASE_COMPLETE_INFO_SAVING'))
          return
        }
        bizDictList = bizDictList.filter(i => i.name)
        // console.log('bizDictList-------', bizDictList)
        if (this.delIds.length) { // 如果有就删除
          const ids = this.delIds.map(i => i.id).toString()
          const names = this.delIds.map(i => i.name).toString()
          await BizDictApi.del({ ids: ids, methods: names })// methods 操作日志需要
          this.delIds = []
          this.addLog({
            i18nKey: 'DELETED_ROUTING_METHODD_LOG', // 删除敷设方法
            object: names,
            names
          })
        }
        if (bizDictList.length) { // 保存/修改
          const res = await BizDictApi.saveBatch([...bizDictList])
          if (!res) {
            this.$message.error(this.$t('SAVEFAILED'))
          }
          this.addLog({
            i18nKey: 'EDITED_LAYING_METHOD_LOG', // 编辑敷设方法
            object: '/'
          })
        }
        this.$message.success(this.$t('SAVE_SUCCESS'))
        this.close('load')
      },
      close(load) {
        this.$emit('close', load)
      },
      addLog(logData) {
        let item = ''
        if (this.parentVM.functionName === 'homeGis') {
          item = 'HOME_GIS_MAP' // 系统首页-GIS展示
        }
        if (this.parentVM.functionName === 'cable') {
          item = 'MENU_CABLE_MANAGER' // 光缆管理
        }
        const obj = {
          item,
          realName: this.getUser.realName,
          terminal: 'EDIT_LAYINGMETHOD', // 编辑敷设方法
          object: logData.object,
          content: JSON.stringify({
            currentUserId: this.getUserId,
            ...logData
          })
        }
        // 记录导出日志
        OperateLogApi.addLog(obj)
      }
    }
  }
</script>

<style lang="scss" scoped>
 @import '@/assets/css/mixin.module.scss';
.tabType{
 @include themeify {
    border-bottom:1px solid themed('tableBorderColor');
 }
 span{
  padding:5px;
  line-height: 25px;
  text-align: center;
  cursor: pointer;
  &.active{
   @include themeify {
     background-color: themed('tabsActiveBgColor');
   }
  }
  &:last-child{
   border: 0;
  }
 }
}
</style>
@/api/basebiz/BizDictApi
